package com.example.juyuanapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.juyuanapp.bean.BookBean;
import com.google.gson.Gson;

import org.json.JSONObject;

import adapter.MyAdapter;

public class BookActivity extends AppCompatActivity {
    ImageView iv_back;
    ListView foodlist;
    int userid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book);
        foodlist=findViewById(R.id.foodlist);
        //获取用户id
        Intent intent=getIntent();
        userid = intent.getIntExtra("userid", 0);
        list();
    }

    private void list() {
        RequestQueue queue= Volley.newRequestQueue(BookActivity.this);
        String url="http://192.168.43.251:8080/food/list";
        JsonObjectRequest request=new JsonObjectRequest(Request.Method.POST, url,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        Gson gson = new Gson();
                        BookBean bookBean = gson.fromJson(jsonObject.toString(), BookBean.class);

                        MyAdapter myAdapter=new MyAdapter(BookActivity.this, bookBean.getData());
                        foodlist.setAdapter(myAdapter);
                        //listView的点击监听
                        foodlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                Intent intent = new Intent(BookActivity.this, DetailActivity.class);
                                intent.putExtra("foodId", i);
                                intent.putExtra("userid", userid);
                                startActivity(intent);
                            }
                        });
                    }
           },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(BookActivity.this,"网络异常",Toast.LENGTH_SHORT).show();
            }
        });
        queue.add(request);
      }
}
